package com.fafa.pos.dao.impl;

import android.content.ContentValues;
import android.database.Cursor;
import com.fafa.pos.dao.DBUtil;
import com.fafa.pos.dao.ICardInfoDao;
import com.fafa.pos.pojo.CardInfo;
import com.fafa.pos.pojo.VipGroupInfo;
import com.fafa.pos.util.DateUtil;

import java.util.List;

/**
 * Created by ZhouBing on 2017/8/10.
 *
 * SQLite  -- T_CARDINFO
 */
public class CardInfoDaoImpl implements ICardInfoDao{

    private DBUtil dbUtil;
    private ConfigDaoImpl configDao;

    public CardInfoDaoImpl(DBUtil dbUtil) {
        this.dbUtil = dbUtil;
        configDao = new ConfigDaoImpl(dbUtil);
    }
    @Override
    public void saveCardInfoList(List<CardInfo> cardInfos) {

        dbUtil.getDB().beginTransaction();

        try{
            for (CardInfo cardInfo:cardInfos) {

                //Id存在则更新不存在新增
                String sql = "select CARD_ID from T_CARDINFO where CARD_ID = ?";
                Cursor cursor = dbUtil.getDB().rawQuery(sql,new String[]{cardInfo.getCardId()});

                ContentValues contentValues = new ContentValues();
                contentValues.put("CARD_ID",cardInfo.getCardId());
                contentValues.put("CARD_CODE",cardInfo.getCardCode());
                contentValues.put("CARD_STATUS",cardInfo.getCardStatus());
                contentValues.put("VIP_ID",cardInfo.getVipId());
                contentValues.put("VALID_DATE",cardInfo.getValidDate());
                contentValues.put("UPDATE_DATE",cardInfo.getUpdate());

                if(cursor.moveToNext()){
                    dbUtil.getDB().update("T_CARDINFO",contentValues," CARD_ID = ?",new String[]{cardInfo.getCardId()});
                }else{
                    dbUtil.getDB().insert("T_CARDINFO",null,contentValues);
                }
                if(cursor!=null){
                    cursor.close();
                }
            }
            configDao.saveItem("T_CARDINFO_UPDATE_DATE", DateUtil.getCurDateStr());
            dbUtil.getDB().setTransactionSuccessful();
        }finally {
            dbUtil.getDB().endTransaction();
            dbUtil.close();
        }
    }

    @Override
    public CardInfo getCard(String cardCode) {

        String sql = "select * from T_CARDINFO where CARD_CODE = ?";
        Cursor cursor = dbUtil.getDB().rawQuery(sql,new String[]{cardCode});
        if(cursor.moveToNext()){
            CardInfo cardInfo = new CardInfo();
            cardInfo.setCardId(cursor.getString(0));
            cardInfo.setCardCode(cursor.getString(1));
            cardInfo.setCardStatus(cursor.getString(2));
            cardInfo.setVipId(cursor.getString(3));
            cardInfo.setValidDate(cursor.getString(4));
            cardInfo.setUpdate(cursor.getString(5));
            return  cardInfo;
        }
        if(cursor!=null){
            cursor.close();
        }
        dbUtil.close();
        return null;
    }



}
